package com.casa.POI.dianping;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Property;

public class SpideCityExecutor extends CityCompositeExecutor {
	

	public SpideCityExecutor(int cityId) {
		super(cityId);
		this.addExecutor(new FetchSearchUrlsExecutor(getCityId()));
		this.addExecutor(new FetchPageUrlsExecutor(getCityId()));
		this.addExecutor(new FetchShopUrlsExecutor(getCityId()));
		this.addExecutor(new FetchShopPagesExecutor(getCityId()));
		this.addExecutor(new ExtractShopInfoExecutor(getCityId()));
	}

	@Override
	public void execute() {
		List<Executor> executors = this.getExecutors();
		for (int step = this.getStep(); step < executors.size(); step = this.stepForward()) {
			Executor executor = executors.get(this.getStep());
			if (executor.getPromptString() != null)
				Console.newLineWriteLine(executor.getPromptString());
			executor.execute();
			Console.writeLine(StringUtils.EMPTY);
		}
	}
	
	public int stepForward() {
		int step = getStep();
		if (step < getExecutors().size()) {
			setStep(step + 1);
		}
		return step + 1;
	}
	
	public int getStep() {
		Session s = SessionManager.getInstance().openSession();
		Criteria c = s.createCriteria(Status.class);
		c.add(Property.forName("cityId").eq(getCityId()));
		c.setMaxResults(1);
		Status status = (Status) c.uniqueResult();
		if (status != null) {
			s.close();
			return status.getStep();
		} else {
			s.beginTransaction();
			status = new Status(getCityId(), 0);
			s.save(status);
			s.getTransaction().commit();
			s.close();
			return 0;
		}
	}

	public void setStep(int step) {
		Session s = SessionManager.getInstance().openSession();
		s.beginTransaction();
		Status status = new Status(getCityId(), step);
		s.saveOrUpdate(status);
		s.getTransaction().commit();
		s.close();
	}
}
